//
//  ViewController.swift
//  Base
//
//  Created by Flutter on 2021/7/7.
//

import UIKit
import Standard
import RxSwift
import RxCocoa


open class ViewController: UIViewController {

    open private(set) var disposeBag: DisposeBag = DisposeBag()
    
    open private(set) var logger = Loggers[typeName]
    
    open private(set) var isFirstLoad: Bool = true
    
    deinit {
        logger.debug("\(typeName) deinit")
    }

}


// MARK: - TypeName

extension ViewController: TypeName {}


// MARK: - Public

public extension ViewController {
    
    
    
    var isInNavigationController: Bool {
        guard let navigationController = navigationController else { return false }
        return navigationController is NavigationController
    }
    
    func addDefaultLeftBarButtonItem(image: UIImage?) {
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            image: image,
            style: .plain,
            target: self,
            action: #selector(back)
        )
    }
    
    @objc
    func back() {
        navigationController?.popViewController(animated: true)
    }
    
}

// MARK: - Override

extension ViewController {
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    override open func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if isChild { return }

        if parent?.isMember(of: ViewController.self) ?? false { return }

        logger.trace("\(typeName) viewWillAppear")
    }

    override open func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        isFirstLoad = false
    }

    override open func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if isChild { return }
        if parent?.isMember(of: ViewController.self) ?? false { return }

        logger.trace("\(typeName) viewWillDisappear")
    }
    
}


// MARK: - Override Config

extension ViewController {
    open var isChild: Bool { false }
    override open var preferredStatusBarStyle: UIStatusBarStyle { .default }
    override open var hidesBottomBarWhenPushed: Bool {
        get { (navigationController?.viewControllers.count ?? 0) > 1 }
        set { super.hidesBottomBarWhenPushed = newValue }
    }

    override open var shouldAutorotate: Bool { true }
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { .portrait }
    override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { .portrait }
}


// MARK: - Private

private extension ViewController {
    func setup() {
        navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
        navigationItem.setHidesBackButton(true, animated: true)
        view.backgroundColor = .systemBackground
    }
}
